package com.luke.exercise.concurrent;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

    private static final int MAX = 5000;
    private static final int MIN = 1000;
    
    //产生随机的工作时间
    private static long getRandomWorkDuration(long min, long max) {
        return (long) (Math.random() * (max -min) + min);
    }
    
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(2);
        Worker w1 = new Worker("lusen", getRandomWorkDuration(MIN,MAX));
        Worker w2 = new Worker("luke" ,getRandomWorkDuration(MIN,MAX));
        
        new Thread(new WorkThread(w1, latch)).start();
        new Thread(new WorkThread(w2, latch)).start();
        
        try {
            latch.await();
            System.out.println("all jobs have been finished!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Worker {
    private String name;//名字
    
    private long workDuration;//工作持续时间
    
    public Worker(String name, long workDuration) {
        this.name = name;
        this.workDuration = workDuration;
    }
    
    public void doWork() {
        System.out.println(name + " begins to work...");
        try{
            Thread.sleep(workDuration);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "has finished the job...");
    }
}

class WorkThread implements Runnable {

    private Worker worker;
    private CountDownLatch latch;
    
    public WorkThread(Worker worker, CountDownLatch latch) {
        this.worker = worker;
        this.latch = latch;
    }
    
    public void run() {
        worker.doWork();
        latch.countDown();
    }
    
}